//
//  UserDetailViewController.m
//  shise
//
//  Created by 毛志鹏 on 14/12/17.
//  Copyright (c) 2014年 MZP. All rights reserved.
//

#import "UserDetailViewController.h"
#import "NetHandler.h"
#import "UIImageView+WebCache.h"
#import "Food.h"
#import "FoodCell.h"
#import "MoreDetailCell.h"
#import "MJRefresh.h"
#import "DataBaseHaneler.h"
#import "SJAvatarBrowser.h"
#import "DetailViewController.h"


@interface UserDetailViewController () <UITableViewDataSource, UITableViewDelegate>
// 视图
@property (nonatomic, retain) UIImageView *userHead;
@property (nonatomic, retain) UIImageView *locationIcon;
@property (nonatomic, retain) UILabel *location;
@property (nonatomic, retain) UIImageView *oneWordIcon;
@property (nonatomic, retain) UILabel *oneWord;
@property (nonatomic, retain) UITableView *tableView;
// 数据
@property (nonatomic, retain) NSString *userHead_url;
@property (nonatomic, retain) NSMutableArray *foodArr;
@property (nonatomic, retain) NSString *refresh;

@end

@implementation UserDetailViewController

- (void)dealloc
{
    [_userHead release];
    [_location release];
    [_oneWord release];
    [_locationIcon release];
    [_oneWordIcon release];
    [_tableView release];
    
    [_userHead_url release];
    [_foodArr release];
    [_refresh release];
    
    [_userApi release];

    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.view.userInteractionEnabled = NO;
    
    // 布局  用户基本信息保持不变  下面加一个tableView
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(5 , 5 + 64, self.view.frame.size.width / 6 + 10, self.view.frame.size.width / 5);
//    button.backgroundColor = [UIColor clearColor];
    [self.view addSubview:button];
    
    
    self.userHead = [[UIImageView alloc] initWithFrame:CGRectMake(0 , 0, self.view.frame.size.width / 6 + 10, self.view.frame.size.width / 5)];
//    self.userHead.backgroundColor = [UIColor whiteColor];
    [button addSubview:self.userHead];
    
    [button addTarget:self action:@selector(fangda:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    [_userHead release];
    
    
    self.locationIcon = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 6 + 15 + 3, 64 + 5, 20, 20)];
//    self.locationIcon.backgroundColor = [UIColor purpleColor];
    self.locationIcon.image = [UIImage imageNamed:@"iconfont-place.png"];
    [self.view addSubview:self.locationIcon];
    [_locationIcon release];
    
    
    
    self.location = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 6 + 40, 64 + 5, 200, 20)];
    self.location.font = [UIFont boldSystemFontOfSize:14];
//    self.location.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.location];
    [_location release];
    
    self.oneWord = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 6 + 40, 64 + 25, self.view.frame.size.width - self.view.frame.size.width / 6 - 50, 50)];
//    self.oneWord.backgroundColor = [UIColor greenColor];
    self.oneWord.font = [UIFont boldSystemFontOfSize:12];
    self.oneWord.numberOfLines = 0;
    [self.view addSubview:self.oneWord];
    [_oneWord release];
    
    self.oneWordIcon = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 6 + 15 + 3, 64 + 40, 20, 20)];
//    self.oneWordIcon.backgroundColor = [UIColor yellowColor];
    self.oneWordIcon.image = [UIImage imageNamed:@"iconfont-xihuan.png"];
    [self.view addSubview:self.oneWordIcon];
    [_oneWordIcon release];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.width / 6 + 85, self.view.frame.size.width, self.view.frame.size.height - self.view.frame.size.width / 6 - 82) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    // 不显示滚动条
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [_tableView release];
    
//    [self.tableView reloadData];
    [self handleData];
    
    [self setupRefresh];

    
    // Do any additional setup after loading the view.
}

// 数据处理方法
- (void)handleData
{
    NSString *str = [NSString stringWithFormat:@"https://api.shiseapp.com/v2/user/%@/?_version=2.5.0&uuid=d08bd82ccb745d7b14803af12131acd7", self.userApi];
    
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *resultError = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];

    
        self.refresh = [[result objectForKey:@"pagination"] objectForKey:@"nextUrl"];
        
        NSArray *arr = [result objectForKey:@"data"];
        
        self.foodArr = [NSMutableArray array];
        for (NSDictionary *tempDic in arr) {
           if ([[tempDic objectForKey:@"type"] isEqualToString:@"ProfileCard"]) {
               
//               NSLog(@"%@", [tempDic objectForKey:@"avatar_hd"]);
               
               self.title = [[tempDic objectForKey:@"user"] objectForKey:@"name"];
               
               self.userHead_url = [tempDic objectForKey:@"avatar_hd"];
               
//                self.userHead_url = [[tempDic objectForKey:@"user"] objectForKey:@"avatar"];
               
                [self.userHead setImageWithURL:[NSURL URLWithString:self.userHead_url] placeholderImage:[UIImage imageNamed:@"tou.jpg"]];
               
                self.location.text = [tempDic objectForKey:@"loc"];
                self.oneWord.text = [tempDic objectForKey:@"desc"];
               self.oneWord.numberOfLines = 2;
        
            } else if ([[tempDic objectForKey:@"type"] isEqualToString:@"MediaCard"]) {
                Food *food = [[Food alloc] initWithDictionary:tempDic];
                [self.foodArr addObject:food];
                [food release];
            }
        }
        [self.tableView reloadData];
    }];
}

// 刷新数据的三个方法
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
#warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新";
    self.tableView.headerRefreshingText = @"正在刷新...";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.tableView.footerRefreshingText = @"正在刷新...";
    
}
// 下拉刷新
- (void)headerRereshing
{
    [self handleData];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        self.view.userInteractionEnabled = YES;
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}
// 上啦加载
- (void)footerRereshing
{
    NSString *str = [NSString stringWithFormat:@"%@&version=2.5.0&uuid=d08bd82ccb745d7b14803af12131acd7", self.refresh];
//    NSLog(@"还有没有接口了呢?::%@", self.refresh);
    if (nil == self.refresh) {
        [self.tableView footerEndRefreshing];
    } else {
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        NSError *resultError = nil;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&resultError];
        
        NSArray *arr = [result objectForKey:@"data"];
        self.refresh = [[result objectForKey:@"pagination"] objectForKey:@"nextUrl"];
        
        // 新建一个数组用来存放上拉刷新后 请求的美食对象
        NSMutableArray *newFoodArr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            Food *food = [[Food alloc] initWithDictionary:dic];
            [newFoodArr addObject:food];
            [food release];
        }
        [self.foodArr addObjectsFromArray:newFoodArr];
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.tableView reloadData];
            
//            NSLog(@"**************");
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
            
        });
        
    }];
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
// UITableView的两个协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.foodArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MoreDetailCell *foodCell = [tableView dequeueReusableCellWithIdentifier:@"food"];
    if (foodCell == nil) {
        foodCell = [[[MoreDetailCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"food"]autorelease];
    }
    Food *food = [self.foodArr objectAtIndex:indexPath.row];
    foodCell.food = food;
    foodCell.praiseNumbers.text = food.likeCount;
    
     //为cell上的按钮添加点击跳转详情的方法
    
    foodCell.foodImageViewButton.tag = 10000 + indexPath.row;
    [foodCell.foodImageViewButton addTarget:self action:@selector(clickPic:) forControlEvents:UIControlEventTouchUpInside];
    
    foodCell.userHeadImageViewButton.tag = 20000 + indexPath.row;
    [foodCell.userHeadImageViewButton addTarget:self action:@selector(clickHead:) forControlEvents:UIControlEventTouchUpInside];
    
    foodCell.praiseImageViewButton.tag = 30000 + indexPath.row;
    [foodCell.praiseImageViewButton addTarget:self action:@selector(clickPraise:) forControlEvents:UIControlEventTouchUpInside];
    
    foodCell.markImagViewButton.tag = 40000 + indexPath.row;
    [foodCell.markImagViewButton addTarget:self action:@selector(clickMark:) forControlEvents:UIControlEventTouchUpInside];
    
    if (food.clickPraiseCount % 2 == 0) {
        
        foodCell.praiseImageView.image = [UIImage imageNamed:@"praiseFont.png"];
    } else {
        
        foodCell.praiseImageView.image = [UIImage imageNamed:@"praiseBehind.png"];
//        foodCell.praiseNumbers.text = @"已赞";
//        NSLog(@"你说呢？");
    }
    if (food.clickMarkCount != 0) {
        
        foodCell.markImageView.image = [UIImage imageNamed:@"markBehind.png"];
    } else {
        
        foodCell.markImageView.image = [UIImage imageNamed:@"mark.png"];
    }


    return foodCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 410;
}


// 点击图片跳转详情
- (void) clickPic:(UIButton *)foodPic
{
    
    [self showNavi];
    
    DetailViewController *foodDetail = [[DetailViewController alloc] init];
    
    foodDetail.detailApi = [[self.foodArr objectAtIndex:foodPic.tag - 10000] objId];
    
    foodDetail.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:foodDetail animated:YES];
    [foodDetail release];
}
// 点击头像跳转用户详情
- (void) clickHead:(UIButton *)userHead
{
    [self showNavi];
    
    UserDetailViewController *userDetail = [[UserDetailViewController alloc] init];
    
    Food *temp = [self.foodArr objectAtIndex:userHead.tag - 20000];
    
    userDetail.userApi = [temp.user objectForKey:@"id"];
    if (userDetail.userApi.length > 0) {
        
        userDetail.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:userDetail animated:YES];
        
    }
    [userDetail release];
}
// 点击“赞”的时候执行的方法
- (void)clickPraise:(UIButton *)button
{
    
    // 当点击赞的时候赞的图片变成红色的同时赞的人数加1
    NSInteger numberOfCell = button.tag - 30000;
    Food *food = [self.foodArr objectAtIndex:numberOfCell];
    if (food.clickPraiseCount % 2 == 0) {
        
        food.clickPraiseCount += 1;
        
        NSString *likeCount = food.likeCount;
        NSInteger likeCountNew = [likeCount integerValue];
        likeCountNew = likeCountNew + 1;
        //    NSNumber *num = [likeCount description];
        food.likeCount = [NSString stringWithFormat:@"%ld", likeCountNew];
        //        self.number = 1;
        [self.tableView reloadData];
        
    } else {
        
        food.clickPraiseCount += 1;
        
        NSString *likeCount = food.likeCount;
        NSInteger likeCountNew = [likeCount integerValue];
        likeCountNew = likeCountNew - 1;
        //    NSNumber *num = [likeCount description];
        food.likeCount = [NSString stringWithFormat:@"%ld", likeCountNew];
        //        self.number = 1;
        [self.tableView reloadData];
    }
}

- (void)fangda:(UIButton *)button
{
//    NSLog(@"放大");
    [SJAvatarBrowser showImage:[button.subviews lastObject]];
}

// 点击“马克”的时候执行的方法
- (void)clickMark:(UIButton *)button
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    if ([def objectForKey:@"userName"] == nil) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];

    } else {
        
        NSInteger numberOfCell = button.tag - 40000;
        Food *food = [self.foodArr objectAtIndex:numberOfCell];
        food.clickMarkCount += 1;
        [self.tableView reloadData];
        NSDictionary *dic = food.user;
        // 将用户信息字典中的用户头像地址取出来赋值给用户头像地址 字符串
        food.userHeadeImageViewAddress = [dic objectForKey:@"avatar"];
        NSLog(@"人物头像地址%@", food.userHeadeImageViewAddress);
        
        // 当收藏本条美食信息的时候就讲本条没事信息存储到本地 当点击我的收藏的时候从本地读取信息 并显示
        DataBaseHaneler *handler = [DataBaseHaneler shareInstance];
        // 打开数据库
        [handler openDB];
        // 创建美食表表
        [handler createFoodTable];
        // 添加一条美食数据
        [handler insertFood:food userName:[def objectForKey:@"userName"]];
        
    }
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
